package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.UserDto;
import com.zzyl.dto.UserPasswordDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.vo.UserPageRoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.RemoteEndpoint;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口实现类
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private DeptMapper deptMapper;

    /**
     * 分页条件查询
     * @param pageNum 页码
     * @param pageSize 条数
     * @param userDto 条件信息
     */
    @Override
    public PageResponse<UserVo> getPage(Integer pageNum, Integer pageSize, UserDto userDto) {
        //分页插件
        PageHelper.startPage(pageNum,pageSize);
        //查询
        List<User> users = userMapper.selectPage(userDto);
        //遍历每一条数据，拿到ID，联查到绑定的角色信息，赋值到每一个数据
        for (User user : users) {
            Long id = user.getId();
            List<Long> roleIds = userRoleMapper.selectByUserIdToRoleId(id);
            List<String> roleNames = userRoleMapper.selectByUserIdToRoleName(id);
            user.setRoleVoIds(roleIds);
            user.setRoleLabels(roleNames);
        }
        //封装结果
        Page<User> result = (Page<User>) users;
        //返回结果
        return PageResponse.of(result,UserVo.class);
    }

    /**
     * 添加用户
     * @param userDto 用户信息
     */
    @Override
    public void addUser(UserDto userDto) {
        //更换映射
        User user = BeanUtil.copyProperties(userDto, User.class);
        //须选择最底层部门
        Long dept = deptMapper.selectSon(user.getDeptNo());
        if (dept > 0){
            throw new BaseException(BasicEnum.USER_INSERT_FAIL_DEPT_NOT_LAST);
        }
        //姓名不可重复
        Long name = userMapper.selectByName(user.getRealName());
        if (name > 0){
            throw new BaseException(BasicEnum.USER_INSERT_FAIL_NAME_REPEAT);
        }
        //邮箱不可重复
        Long email = userMapper.selectByEmail(user.getEmail());
        if (email > 0){
            throw new BaseException(BasicEnum.USER_INSERT_FAIL_EMAIL_REPEAT);
        }
        //添加用户
        user.setDataState("0");
        String password = "888itcast.CN764%...";
        user.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
        userMapper.insert(user);
        //绑定角色
        UserRole userRole = new UserRole();
        for (Long roleId : user.getRoleVoIds()) {
            userRole.setDataState("0");
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }
    }

    /**
     * 修改用户
     * @param userDto 修改信息
     */
    @Override
    public void updateUser(UserDto userDto) {
        //更换映射
        User user = BeanUtil.copyProperties(userDto, User.class);
        //姓名不可重复【除自身】
        Long name = userMapper.selectByNameWithoutSelf(user.getRealName(),user.getId());
        if (name > 0){
            throw new BaseException(BasicEnum.USER_UPDATE_FAIL_NAME_REPEAT);
        }
        //邮箱不可重复【除自身】
        Long email = userMapper.selectByEmailWithoutSelf(user.getEmail(),user.getId());
        if (email > 0){
            throw new BaseException(BasicEnum.USER_UPDATE_FAIL_EMAIL_REPEAT);
        }
        //删除所有绑定角色
        userRoleMapper.deleteAll(user.getId());
        //添加绑定角色
        UserRole userRole = new UserRole();
        for (Long roleId : user.getRoleVoIds()) {
            userRole.setDataState("0");
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }
    }

    /**
     * 修改用户状态
     * @param id 用户ID
     * @param status 用户状态
     */
    @Override
    public void updateUserStatus(Long id, String status) {
        userMapper.updateStatus(id,status);
    }

    /**
     * 用户列表
     * @param realName 用户姓名
     */
    @Override
    public List<UserVo> getUserList(String realName) {
        List<UserVo> list = userMapper.getList(realName);
        return list;
    }

    /**
     * 删除用户
     * @param userId 用户ID
     */
    @Override
    public void removeUser(String userId) {
        //启用状态不可删除
        String status = userMapper.selectStatus(userId);
        if (status.equals("0")){
            throw new BaseException(BasicEnum.USER_DELETE_FAIL_INUSE);
        }
    }

    /**
     * 重置用户密码
     * @param userId 用户ID
     */
    @Override
    public void resetPassword(String userId) {
        UserPasswordDto userPasswordDto = new UserPasswordDto();
        userPasswordDto.setUserId(userId);
        String password = "888itcast.CN764%...";
        userPasswordDto.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
        userMapper.updatePassword(userPasswordDto);
    }


}
